package dal

import (
	"gitee.com/xxhsjp/x-core/database/models"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

func PagingQuery[T any](db *gorm.DB, pagingInfo models.PagingInfo) (*models.PagingResult[T], error) {
	var count int64
	if err := db.Count(&count).Error; err != nil {
		return nil, errors.WithStack(err)
	}

	if pagingInfo.Page != 0 && pagingInfo.Size != 0 {
		offset := (pagingInfo.Page - 1) * pagingInfo.Size
		db = db.Limit(pagingInfo.Size).Offset(offset)
	}

	dest := make([]T, 0)
	err := db.Scan(&dest).Error
	if err != nil {
		return nil, errors.WithStack(err)
	}

	result := new(models.PagingResult[T])
	result.Count = int(count)
	result.PagingInfo = pagingInfo
	result.Data = dest

	return result, nil
}
